<?PHP	
include('config/config.php');
require('php/functions.php');
	//Connect to database
	$conn = mysql_connect($cfg["connection"]["host"], $cfg["connection"]["userName"], $cfg["connection"]["password"]) 
		or die ('Error Cannot Connect to MySQL');
	@mysql_select_db($cfg["connection"]["database"]) or die( "Unable to select database");
	
	$query = "CREATE TABLE itemRep LIKE item;";
	$result = mysql_query($query);
	$query = "INSERT INTO itemRep SELECT * FROM item;";
	$result = mysql_query($query);
	
	$query = "SELECT curdate() AS date";
	$result = mysql_query($query);
	$curdate = mysql_fetch_array($result);
	$curdate = $curdate['date'];
	
	$tbl_name = $cfg['tbl']['shopLocation'];
	$query = "SELECT shopId FROM $tbl_name";
	$result = mysql_query($query);
	$shopIDs = array();
	while ($shopID = mysql_fetch_assoc($result, MYSQL_NUM)) $shopIDs[] = $shopID[0];
	$noShop = mysql_num_rows($result);
	
	
	/***************************************/
	
	foreach ($shopIDs as $shopID) {
		$filename = "/usr/local/apache/htdocs/admin-panel/uploads/ReStock_"."$shopID"."_"."$curdate.txt";
		$file = fopen( $filename, "r" );
		if (!$file) {
			continue;
		}
		$filesize = filesize( $filename );
		$filetext = fread( $file, $filesize );
		fclose( $file );
		
		$content = explode("\n", $filetext);
		foreach ($content as $line)	{
			list($barcode, $EODStock, $deltaStock) = explode(":",$line);
			$deltaStock = intval($deltaStock);
			$EODStock = intval($EODStock);
			$query = "INSERT INTO hq.itemtmp VALUES('".$barcode."', '".$shopID."', '".$deltaStock."')
						ON DUPLICATE KEY UPDATE itemId = '".$barcode."', shopId = '".$shopID."', deltaStock = '".$deltaStock."';";
			$result = mysql_query($query);
		}
	}
	
	$query = "SELECT itemId AS itemId, SUM(deltaStock) AS requestedStock FROM hq.itemtmp GROUP BY itemId";
	$result = mysql_query($query);
	$items = array();
	while ($item = mysql_fetch_assoc($result, MYSQL_NUM)) $items[] = $item;
	
	foreach ($items as $item) {
		$query = "SELECT * FROM hq.item WHERE itemId = $item[0];";
		$result = mysql_query($query);
		$row = mysql_fetch_assoc($result);
		if (intval($row['local_stock']) < intval($item[1])) {
			//HQ has too few stocks
			$query = "DELETE FROM hq.itemtmp WHERE itemId = $item[0]";
			$result = mysql_query($query);
		}
		else {
			$query = "UPDATE itemRep SET itemRep.local_stock = itemRep.local_stock - $item[1] WHERE itemRep.itemId = $item[0]";
			$result = mysql_query($query);
		}
	}
	
	$query = "SELECT curdate() + INTERVAL 1 DAY AS date";
	$result = mysql_query($query);
	$nextdate = mysql_fetch_array($result);
	$nextdate = $nextdate['date'];
	
	//mkdir("/usr/local/apache/htdocs/admin-panel/downloads");
	foreach ($shopIDs as $shopID) {
		$filename = "/usr/local/apache/htdocs/admin-panel/downloads/Inventory_"."$shopID"."_"."$nextdate.txt";
		$file = fopen($filename, "w");
		
		$query = "SELECT itemRep.itemId, itemName, price, category, manufacturer, local_stock, minimum_stock, bundle_unit, deltaStock
					FROM itemRep LEFT JOIN (SELECT itemId, deltaStock FROM itemtmp WHERE shopId=$shopID) AS tmp ON (itemRep.itemId = tmp.itemId)";
		$result = mysql_query($query) or die(mysql_error());
		$items = array();
		while ($item = mysql_fetch_assoc($result, MYSQL_NUM)) $items[] = $item;
		
		foreach($items as $item) {
			$reStock = floor($item[8]);
			if ($reStock == "") {
				$reStock = floor($item[5] / $noShop);
				fwrite($file, "$item[1]:$item[3]:$item[4]:$item[0]:$item[2]:$reStock:$item[6]:$item[7]\n");
				//println("$item[1]:$item[3]:$item[4]:$item[0]:$item[2]:$reStock:$item[6]:$item[7]");
			}
			else {
				$reStock += floor($item[5] / $noShop);
				if ($reStock < 0) $reStock = 0;					//issue: ShopPC allowed orders to be passed upstream even if there are not sufficient stocks
				fwrite($file, "$item[1]:$item[3]:$item[4]:$item[0]:$item[2]:$reStock:$item[6]:$item[7]\n");
				//println("$item[1]:$item[3]:$item[4]:$item[0]:$item[2]:$reStock:$item[6]:$item[7]");
			}
		}
		fclose($file);
	}	
	$query = "DELETE FROM hq.itemtmp WHERE 1";
	$result = mysql_query($query);
	$query = "DROP TABLE hq.itemRep;";
	$result = mysql_query($query);
	header("Location: ./index.php");
?>
